package task.threads;

import java.util.concurrent.*;

public class CountDownLatchMethod {

    private final static int threadCount = 10;

    public static void main(String[] args) throws InterruptedException {

        long start=System.currentTimeMillis();

        // 在这里创建一个线程或线程池，
        ExecutorService exec = Executors.newCachedThreadPool();
        // 异步执行 下面方法
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        StringBuilder sbr= new StringBuilder();
        for (int i = 0; i < threadCount; i++) {
            int inparm = i;
            exec.execute(() -> {
                try {
                    System.out.println("thread"+inparm+ "start");
                    int result = sum(inparm+10);
                    if(inparm+1==threadCount){
                        sbr.append("thread").append(inparm).append(":").append(result);
                    }else{
                        sbr.append("thread").append(inparm).append(":").append(result).append(",");
                    }
                    System.out.println("thread"+inparm+ "end");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        countDownLatch.await();

        String result = sbr.toString();
        String[] strs = result.split(",");
        for (int i = 0; i < strs.length; i++){
            System.out.println(strs[i]);
        }
        // 确保  拿到result 并输出

        System.out.println("使用时间："+ (System.currentTimeMillis()-start) + " ms");

        // 然后退出main线程
    }

    private static int sum(int i) {
        return fibo(i);
    }

    private static int fibo(int a) {
        if ( a < 2)
            return 1;
        return fibo(a-1) + fibo(a-2);
    }
}
